<template>
    <div class="view">
        <nav-bar title="选择支付方式" :fixed="false">
            <div class="back" slot="left" @click="back">
                <i class="iconfont icon-fanhui"></i>
            </div>
        </nav-bar>
        <div class="price-box">
            <span>支付金额</span>
            <span class="price">{{total | floatZero}}</span>
        </div>
        <div class="pay-type-list">
            <cube-radio-group>
                <div class="pay-type-item" @click="payType = '2'">
                    <svg class="pay-type-svg" aria-hidden="true">
                        <use xlink:href="#icon-weixin"></use>
                    </svg>
                    <div class="pay-type-text">
                        <span class="text">微信支付</span>
                        <span>推荐使用微信支付</span>
                    </div>
                    <cube-radio :option="{value:'2'}" v-model="payType" :hollowStyle="true"></cube-radio>
                </div>
                <div class="pay-type-item" @click="payType = '1'" v-if="!isWechatBrowser">
                    <svg class="pay-type-svg" aria-hidden="true">
                        <use xlink:href="#icon-zhifubao"></use>
                    </svg>
                    <div class="pay-type-text">
                        <span class="text">支付宝支付</span>
                    </div>
                    <cube-radio :option="{value:'1'}" v-model="payType" :hollowStyle="true"></cube-radio>
                </div>
                <div class="pay-type-item" @click="payType = '3'" v-if="orderType!=='recharge'">
                    <svg class="pay-type-svg" aria-hidden="true">
                        <use xlink:href="#icon-yibaoyue"></use>
                    </svg>
                    <div class="pay-type-text">
                        <span class="text">账户余额支付</span>
                        <span>可用余额¥{{user.money}}</span>
                    </div>
                    <cube-radio :option="{value:'3'}" v-model="payType" :hollowStyle="true"></cube-radio>
                </div>
            </cube-radio-group>
        </div>
        <div class="order-channel-btn" @click="confirm">确认支付</div>
        <!--        <cube-form ref="alipayForm" :schema="schema" :action="model.action" :model="model" :immediate-validate="false" :options="options"></cube-form>-->
        <div class="pay-form-wrap" style="display: none">
            <form :action="action" method='POST' ref="alipayForm">
                <input v-for="(value,key) in form" :name="key" v-model="form[key]" readonly="readonly">
            </form>
        </div>
    </div>
</template>

<script lang="ts">
    import {Component, Vue, Watch} from "vue-property-decorator";
    import Scene from "@/render/Scene";
    import Http from "@/service/Http";

    import {Getter, Action, State, Mutation} from "vuex-class";
    import {InterfaceUser} from "@/interface/InterfaceUser";
    import CommonUnit from "@/unit/CommonUnit";
    import Heart from "@/unit/Heart";
    import UserEntity from "@/entity/UserEntity";
    import {exitUser} from "@/store/dispatches";
    import NavBar from "@/components/aui/NavBar.vue";

    @Component({
        components: {
            NavBar
        }
    })
    export default class OrderChannel extends Scene {
        private payType: string = "2";
        private model: any = {};
        private action: string = "https://openapi.alipay.com/gateway.do?charset=utf-8";
        private isWechatBrowser: boolean = CommonUnit.wechatBrowser();

        @State("UserStore")
        public user!: InterfaceUser;


        @State("DeviceStore")
        private device: any;

        private form: any = {};
        private type: number = 0;
        private status: number = 0;
        private realOrderIds: string = "";
        private total: number = 0;
        private payToast: any = "";
        private alipayAppParameter: string = "";

        private back() {
            const orderType = String(this.$route.query.orderType);
            if (orderType === "expert") {
                this.redirectTo({
                    name: "expertList"
                });
            } else if (orderType === "recharge") {
                this.redirectTo({
                    name: "mineMoneyRecharge"
                });
            } else if (orderType === "upgrade") {
                if (this.$route.query.referer === "matchmakerRank") {
                    this.redirectTo({
                        name: "matchmakerRank"
                    });
                } else {
                    this.redirectTo({
                        name: "mineMemberRank"
                    });
                }
            } else {
                this.navigateBack();
            }

        }

        private get orderIds(): string {
            return String(this.$route.query.orderIds || 0);
        }

        private get orderType(): string {
            return String(this.$route.query.orderType || "shop");
        }

        private mounted() {
            this.$nextTick(() => {
                this.payType = "2";
            });
            this.calcTotal();
        }

        private async calcTotal(): Promise<any> {
            const res = await Http.get(this.api.calcTotalAmountByIds, {ids: this.orderIds, type: this.orderType}, {token: this.user.token});
            if (res.code === 1) {
                if (res.data.orderIds.length === 0) {
                    this.payToast = (<any> this).$createToast({
                        txt: "订单已完成支付",
                        time: 1000,
                        mask: true,
                        onTimeout: () => {
                            this.redirectTo({
                                name: "orderList"
                            });
                        }
                    }).show();
                } else {
                    this.realOrderIds = res.data.orderIds.join(",");
                    this.total = res.data.total_amount;
                }

            } else {
                this.globalSingleResultToast(res);
            }
            console.log(res);
        }


        private async confirm(): Promise<any> {
            this.payToast = (<any> this).$createToast({
                txt: "正在发起支付",
                time: 0,
                mask: true,
                zIndex: 201,
            }).show();
            try {
                const res = await Http.post(this.api.orderPay, {
                    type: this.orderType,
                    ids: this.realOrderIds,
                    pay_type: this.payType,
                    app: CommonUnit.wechatBrowser() ? 2 : (this.device.status ? 1 : 0),
                    return_url: `${location.origin}${location.pathname}#${this.redirectUrlString}`
                }, {token: this.user.token});
                if (res.code === 1) {
                    this.type = res.data.type;
                    this.status = res.data.status;
                    this.action = res.data.action;
                    this.form = res.data.form || {};
                    this.alipayAppParameter = Object.keys(this.form)
                        .map((k) => `${encodeURIComponent(k)}=${encodeURIComponent(this.form[k])}`)
                        .join("&");
                    console.log(this.alipayAppParameter);
                    this.$nextTick(() => {
                        setTimeout(() => {
                            // this.payToast.hide();
                            this.webPayHandle(res);
                            // (<any> this).$refs.alipayForm.submit(true);
                        }, 1200);
                    });
                } else {
                    this.payToast = (<any> this).$createToast({
                        txt: res.msg,
                        type: "warn",
                        time: 2000,
                        mask: false,
                        zIndex: 201,
                    }).show();
                }
            } catch (e) {
                this.payToast = (<any> this).$createToast({
                    txt: "支付发生错误，请稍后再试",
                    type: "error",
                    time: 2000,
                    mask: true,
                    zIndex: 201,
                }).show();
            }
        }

        private get redirectUrl(): any {
            if (this.orderType === "upgrade") {
                let name = "";
                if (this.user.type === 1) {
                    name = "mine";
                } else {
                    name = "matchmakerMine";
                }
                return {
                    name: name,
                };
            } else if (this.orderType === "recharge") {
                return {
                    name: "mineIncome",
                };
            } else if (this.orderType === "expert") {
                return {
                    name: "expertList",
                };
            } else {
                if (this.realOrderIds.split(",").length > 1) {
                    return {
                        name: "orderList",
                    };
                } else {
                    return {
                        name: "orderDetail",
                        query: {
                            orderId: this.realOrderIds
                        }
                    };
                }
            }
        }

        private get redirectUrlString(): any {
            if (this.orderType === "upgrade") {
                return "mine";
            } else if (this.orderType === "recharge") {
                return "/mine/income";
            } else if (this.orderType === "expert") {
                return "/expert/list";
            } else {
                if (this.realOrderIds.split(",").length > 1) {
                    return "/order/list";
                } else {
                    return `/order/detail?orderId=${this.realOrderIds}`;

                }
            }
        }

        private webPayHandle(res: any) {
            switch (String(this.type)) {
                case "1":
                    if (this.device.status) {
                        try {
                            cordova.plugins.alipay.payment(this.alipayAppParameter, (res: any) => {
                                this.payToast = (<any> this).$createToast({
                                    txt: `${String(res.resultStatus) === "9000" ? "订单支付成功" : "支付请求已受理，等候支付渠道确认"}，正在返回订单页`,
                                    type: "correct",
                                    time: 1000,
                                    mask: true,
                                    onTimeout: () => {
                                        this.redirectTo(this.redirectUrl);
                                    }
                                }).show();
                            }, (error: any) => {
                                this.payToast = (<any> this).$createToast({
                                    txt: `支付失败：${String(error.resultStatus) === "6001" ? "用户取消支付" : "其它支付错误"}，请重新支付`,
                                    type: "error",
                                    time: 2000,
                                    mask: true,
                                    onTimeout: () => {
                                        this.redirectTo(this.redirectUrl);
                                    }
                                }).show();
                            });
                        } catch (e) {
                            (<any> this).$refs.alipayForm.submit(true);
                        }
                    } else {
                        (<any> this).$refs.alipayForm.submit(true);
                    }
                    break;
                case "2":
                    if (this.device.status) {
                        Wechat.sendPaymentRequest({
                            partnerid: res.data.partnerid,
                            prepayid: res.data.prepayid,
                            timestamp: res.data.timestamp,
                            noncestr: res.data.noncestr,
                            sign: res.data.sign,
                            appid: res.data.appid
                        }, () => {
                            this.payToast = (<any> this).$createToast({
                                txt: "订单支付成功，等候支付渠道确认正在返回订单页",
                                type: "correct",
                                time: 1000,
                                mask: true,
                                onTimeout: () => {
                                    this.redirectTo(this.redirectUrl);
                                }
                            }).show();
                        }, (error: string) => {
                            this.payToast = (<any> this).$createToast({
                                txt: `支付失败：${String(error)}`,
                                type: "error",
                                time: 2000,
                                mask: true,
                                onTimeout: () => {
                                    this.redirectTo(this.redirectUrl);
                                }
                            }).show();
                        });

                    } else if (CommonUnit.wechatBrowser()) {
                        // todo微信支付
                        const that = this;
                        // const data={
                        //     appId: res.data.appid,
                        //     nonceStr: res.data.nonce_str,
                        //     package: 'prepay_id='+res.data.prepay_id,
                        //     signType: 'MD5',
                        //     paySign: res.data.sign,
                        //     timeStamp: res.data.mch_id,
                        // };
                        function onBridgeReady() {
                            WeixinJSBridge.invoke(
                                "getBrandWCPayRequest", res.data,
                                function(res: any) {
                                    if (res.err_msg == "get_brand_wcpay_request:ok") {
                                        // 使用以上方式判断前端返回,微信团队郑重提示：
                                        //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                                        that.payToast = (<any> that).$createToast({
                                            txt: "订单支付成功，等候支付渠道确认正在返回订单页",
                                            type: "correct",
                                            time: 1000,
                                            mask: true,
                                            onTimeout: () => {
                                                that.redirectTo(that.redirectUrl);
                                            }
                                        }).show();
                                    } else {
                                        that.payToast = (<any> that).$createToast({
                                            txt: `支付失败!`,
                                            type: "error",
                                            time: 2000,
                                            mask: true,
                                            onTimeout: () => {
                                                that.redirectTo(that.redirectUrl);
                                            }
                                        }).show();
                                    }
                                });
                        }

                        if (typeof WeixinJSBridge == "undefined") {
                            if (document.addEventListener) {
                                document.addEventListener("WeixinJSBridgeReady", onBridgeReady, false);
                            } else if ((document as any).attachEvent) {
                                (document as any).attachEvent("WeixinJSBridgeReady", onBridgeReady);
                                (document as any).attachEvent("onWeixinJSBridgeReady", onBridgeReady);
                            }
                        } else {
                            onBridgeReady();
                        }
                    } else {
                        location.href = res.data.mweb_url;
                    }
                    break;
                default:
                    if (String(this.status) === "1") {
                        this.payToast = (<any> this).$createToast({
                            txt: "支付成功，正在返回订单",
                            type: "correct",
                            time: 1000,
                            mask: true,
                            onTimeout: () => {
                                this.redirectTo(this.redirectUrl);
                            }
                        }).show();
                    } else {
                        this.payToast = (<any> this).$createToast({
                            txt: "支付失败，可能是余额不足，请充值～",
                            type: "error",
                            time: 1000,
                            mask: true,
                            onTimeout: () => {
                                this.navigateTo({
                                    name: "mineMoneyRecharge"
                                });
                            }
                        }).show();
                    }
            }
        }
    }
</script>

<style scoped lang="stylus">
    .view
        width 100vw;
        height 100vh;
        background $theme-page-common-background-color;

        .price-box
            background #fff;
            height 120px;
            display flex;
            flex-direction column;
            justify-content center;
            align-items center;
            font-size 14px;
            color #909399;

            .price
                font-size 25px;
                color #303133;
                margin-top 6px;

                &::before
                    content '￥';
                    font-size 16px;

        .pay-type-list
            margin-top 10px;
            background #fff;
            padding-left 30px;

            .pay-type-item
                height 60px;
                padding 10px 0;
                display flex;
                justify-content space-between;
                align-items center;
                padding-right 30px;
                font-size 15px;
                position relative;

                >>> .cube-radio
                    font-size 17px;

                .pay-type-svg
                    width 33px;
                    height 33px;

                .pay-type-text
                    padding-left 12px;
                    flex 1;
                    display flex;
                    flex-direction column;
                    font-size 11px;
                    color #999;
                    padding-right 20px;

                    .text
                        padding-bottom 3px;
                        font-size 16px;
                        color #333;
                        margin-bottom 2px;

                >>> .cube-radio
                    padding 0;

        .order-channel-btn
            display flex;
            align-items center;
            justify-content center;
            width 320px;
            height 40px
            margin 40px auto 15px;
            font-size 15px;
            color #fff;
            background-color $theme-common-color;
            border-radius 5px;
            box-shadow 1px 2px 5px rgba(219, 63, 96, 0.4);


</style>
